﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ThisIsTheHandOfFate
{
    class Config
    {
        public List<int> AllPowers = new List<int>();
        public List<string> AllNames = new List<string>();

        public string ToJson()
        {
            return LitJson.JsonMapper.ToJson(this);
        }

        public static Config FromJson(string jsonStr)
        {
            Config res = null;
            try
            {
                res = LitJson.JsonMapper.ToObject<Config>(jsonStr);
            }
            catch (Exception)
            {
                Console.WriteLine("不合法的配置信息：{0}", jsonStr);
            }

            return res;
        }

        public static Config FromFile(string fileName)
        {
            string jsonStr = File.ReadAllText(fileName);
            return FromJson(jsonStr);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            int sum = 0;
            for (int i = 0; i < AllPowers.Count; i++)
            {
                sum += AllPowers[i];
            }

            for (int i = 0; i < AllPowers.Count; i++)
            {
                sb.Append(string.Format("几率：{0:0.0}% \t 名称：{1} \n", ((float)AllPowers[i] / (float)sum) * 100, AllNames[i]));
            }

            return sb.ToString();
        }
    }

    class Program
    {
        public static string DefaultJsonFile = @"Config.json";
        static void Main(string[] args)
        {
            string filePath = DefaultJsonFile;
            FileInfo fileInfo = new FileInfo(filePath);
            if (!fileInfo.Exists)
            {
                int input = -1;
                while (input != 1 && input != 2)
                {
                    Console.WriteLine("未检测到配置文件！请选择操作：");
                    Console.WriteLine("1、新建一个配置文件");
                    Console.WriteLine("2、输入配置文件位置");

                    int.TryParse(Console.ReadLine(), out input);
                }
                switch (input)
                {
                    case 1:
                        filePath = CreateConfig(); break;
                    case 2:
                        filePath = ReadConfigPath(); break;
                }
            }
            else
            {
                Console.WriteLine("检测到配置文件，信息如下，是否读取？(Y/N)");
                Console.WriteLine(Config.FromFile(filePath).ToString());
                string input = String.Empty;
                while (!input.Equals("Y") && !input.Equals("y") && !input.Equals("N") && !input.Equals("n"))
                {
                    input = Console.ReadLine();
                }

                switch (input)
                {
                    case "y":
                        break;
                    case "Y":
                        break;

                    case "n":
                        filePath = CreateConfig();
                        break;
                    case "N":
                        filePath = CreateConfig();
                        break;
                }
            }

            Config config = LoadFromPath(filePath);

            ConsoleKeyInfo inp = new ConsoleKeyInfo();
            do
            {
                HandOfFate(config);
                Console.WriteLine("按下Esc退出，按下键盘任意键再抽");
                inp = Console.ReadKey();
            } while (inp.Key != ConsoleKey.Escape);

        }

        static string CreateConfig()
        {
            Console.Clear();
            Console.WriteLine("开始新建配置。");
            int priceCount = -1;
            while (priceCount < 0)
            {
                Console.WriteLine("有几个奖项呢？");
                int.TryParse(Console.ReadLine(), out priceCount);
            }

            Config newConfig = new Config();
            for (int i = 0; i < priceCount; i++)
            {
                string name = String.Empty;
                int power = -1;

                Console.Clear();
                Console.WriteLine("请输入第{0}个奖项的信息：", i + 1);

                Console.WriteLine("名字：");
                name = Console.ReadLine();

                Console.WriteLine("权重：");
                while (power <= 0)
                {
                    int.TryParse(Console.ReadLine(), out power);
                }
                newConfig.AllNames.Add(name);
                newConfig.AllPowers.Add(power);
            }

            Console.Clear();
            Console.WriteLine("配置完成！开始输出文件");
            File.WriteAllText(DefaultJsonFile, newConfig.ToJson());

            return DefaultJsonFile;
        }

        static string ReadConfigPath()
        {
            Console.Clear();
            Console.WriteLine("开始读取配置文件信息。");
            string path = String.Empty;
            while (string.IsNullOrEmpty(path))
            {
                Console.WriteLine("请输入配置文件位置（带后缀名）：");
                path = Console.ReadLine();
                if (Config.FromFile(path) == null)
                {
                    path = String.Empty;
                }
            }

            return path;
        }

        static Config LoadFromPath(string path)
        {
            return Config.FromFile(path);
        }

        static void HandOfFate(Config config)
        {
            Console.Clear();
            Console.WriteLine("抽奖池：");
            Console.WriteLine(config.ToString());

            List<int> power = config.AllPowers;
            List<string> name = config.AllNames;

            string yourName = String.Empty;
            while (string.IsNullOrEmpty(yourName))
            {
                Console.WriteLine("大侠请输入尊姓大名！");
                yourName = Console.ReadLine();
            }

            int sum = 0;
            for (int i = 0; i < power.Count; i++)
            {
                sum += power[i];
            }

            Random r = new Random();
            int pointer = r.Next(1, sum + 1);

            for (int i = 0; i < power.Count; i++)
            {
                pointer -= power[i];
                if (pointer <= 0)
                {
                    Console.WriteLine("恭喜 {0} 抽中了 {1}", yourName, name[i]);
                    break;
                }
            }

            Console.ReadLine();
        }
    }
}
